﻿<%@ WebHandler Language="C#" Class="UploadHeadPic" %>

using System;
using System.Web;
using Chenxin.Lib.Utility;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.IO;

public class UploadHeadPic : AjaxHandlerBase
{

    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        if (!string.IsNullOrEmpty(context.Request.Params["op"]))
        {
            //处理类型
            string strOperate = context.Request.Params["op"];

            switch (strOperate.Trim())
            {
                case "fileupload":
                    FileUpload(context, Constants.FilePath_HeadPic);
                    break;
                case "save_avata":
                    SaveAvata(context);
                    break;
                case "camera":
                    SaveCamera(context);
                    break;
                default:
                    break;
            }
        }
    }

    /// <summary>
    /// 本地上传头像(未截取的)
    /// 一个参数(头像保存的路径)
    /// </summary>
    /// <param name="context"></param>
    /// <param name="strFile"></param>
    public void FileUpload(HttpContext context, string strFile)
    {
        try
        {
            Random rd = new Random();
            HttpPostedFile file = context.Request.Files["FileData"];

            string savePath = context.Server.MapPath(Constants.DIRECTORY + strFile);
            string fileName = file.FileName.ToString();
            string saveId = DateTime.Now.ToString("yyyyMMddhhmmss") + rd.Next(100, 999).ToString();
            string saveName = saveId + fileName.Substring(fileName.LastIndexOf('.'));

            if (file != null)
            {
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                file.SaveAs(savePath + saveName);
                //context.Response.Write("<script type=\"text/javascript\">window.parent.hideLoading();window.parent.buildAvatarEditor('" + saveName + "','" + Constants.DIRECTORY + strFile + saveName + "','photo');</script>");
                context.Response.Write(string.Format("{{success:1,msg:'文件上传成功！',data:{{picid:'{0}',picurl:'{1}'}}}}", saveName, Constants.DIRECTORY + strFile + saveName));

            }
            else
            {
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "文件上传失败，请重试！", ""));
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }

    }

    /// <summary>
    /// 保存Flash截取的上传头像
    /// 公两个(Big和Small一先一后)
    /// </summary>
    /// <param name="context"></param>
    public void SaveAvata(HttpContext context)
    {
        try
        {
            if (context.Request.Params["type"].Trim().Equals("big") || context.Request.Params["type"].Trim().Equals("small"))
            {
                string saveName = context.Request.Params["photoId"].ToString();
                string savePath = context.Server.MapPath(Constants.DIRECTORY + Constants.FilePath_HeadPic + context.Request.Params["type"] + "/");

                byte[] bytes = context.Request.BinaryRead(context.Request.TotalBytes);
                Stream str = new MemoryStream(bytes);
                System.Drawing.Image image = System.Drawing.Image.FromStream(str);
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                image.Save(savePath + saveName);

                string[] strUrl = { saveName };

                clsData data = new clsData();
                clsPic Pic = new clsPic();
                data.urls = strUrl;

                Pic.status = 1;
                Pic.statusText = "上传成功!";
                Pic.data = data;

                Chenxin.Lib.Passport.Entity.Hr_UserInfo model = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(CurrentUserInfo.UserId);
                Chenxin.Lib.Cache.CacheService cs = null;
                if (context.Request.Params["type"].Trim().Equals("big"))
                {
                    model.PicUrl = Constants.FilePath_HeadPic + context.Request.Params["type"] + "/" + saveName.ToString();
                    Chenxin.Lib.Passport.DAL.Hr_UserInfo.Update(model);
                }
                else if (context.Request.Params["type"].Trim().Equals("small"))
                {
                    model.PicUrlSmall = Constants.FilePath_HeadPic + context.Request.Params["type"] + "/" + saveName.ToString();
                    Chenxin.Lib.Passport.DAL.Hr_UserInfo.Update(model);
                    //删除最初上传的头像
                    File.Delete(context.Server.MapPath(Constants.DIRECTORY + Constants.FilePath_HeadPic) + saveName);
                }
                string strKeyUser = string.Format(Chenxin.Lib.Cache.CacheDataType.USER, CurrentUserInfo.UserId);
                cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                cs.Delete(strKeyUser);
                
                cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HR);
                string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_USER, CurrentUserInfo.UserId.ToString());
                //删除缓存列表
                cs.Delete(strCacheKey);
                context.Response.Write(Chenxin.Lib.Utility.JsonHelp.Convert2Json(Pic));

            }
        }
        catch (Exception ex)
        {
            context.Response.Write("<script type=\"text/javascript\">window.parent.hideLoading();alert('上传头像失败!" + ex.Message + "');</script>");
        }
    }

    public class clsPic
    {
        public clsData data;
        public int status;
        public string statusText;
    }

    public class clsData
    {
        public string[] urls;
    }

    /// <summary>
    /// 保存通过摄像头截图的头像
    /// </summary>
    /// <param name="context"></param>
    public void SaveCamera(HttpContext context)
    {
        try
        {
            Random rd = new Random();
            string saveId = DateTime.Now.ToString("yyyyMMddhhmmss") + rd.Next(100, 999).ToString();
            string savePath = context.Server.MapPath(Constants.DIRECTORY + Constants.FilePath_HeadPic + "camera/");
            byte[] bytes = context.Request.BinaryRead(context.Request.TotalBytes);
            Stream str = new MemoryStream(bytes);
            System.Drawing.Image image = System.Drawing.Image.FromStream(str);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            image.Save(savePath + saveId + ".jpg");

            string[] strUrl = { saveId };

            clsData data = new clsData();
            clsPic Pic = new clsPic();
            data.urls = strUrl;

            Pic.status = 1;
            Pic.statusText = "上传成功!";
            Pic.data = data;

            context.Response.Write(Chenxin.Lib.Utility.JsonHelp.Convert2Json(Pic));

        }
        catch (Exception ex)
        {
            context.Response.Write("<script type=\"text/javascript\">window.parent.hideLoading();alert('上传头像失败!" + ex.Message + "');</script>");
        }
    }
}